package cn.kgc.javaweb.listener;

import cn.kgc.javaweb.entity.User;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: mosin
 * @version: v1.0  2022/5/31
 * 监听session域中值的改变
 */
@WebListener
public class MySessionAttributeListener  implements HttpSessionAttributeListener {
    //key 用户名  value  session   admin  ->  session
    private Map<String, HttpSession> map = new HashMap<>();
    // session中添加值
    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {  // 单点登录
        //获取添加在session中的key
        String name = event.getName();
        //获取添加在session中的value
        User user = (User)event.getValue();
        // session 中存储的key
        if("user".equals(name)){
            //获取用户名
            String username = user.getUsername();
            //判定当前map集合中是否已经存在当前用户名对应的session
            if(map.containsKey(username)){
                //根据用户名 取出在map集合中对应的session
                HttpSession httpSession = map.get(username);
                //销毁当前用户对应的session
                httpSession.invalidate();
            }
            //添加当前用户对应的新的session
            map.put(username, event.getSession());
        }
    }
    // session中删除值
    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
        String name = event.getName();
        Object value = event.getValue();
        System.out.println("删除 name = " + name);
        System.out.println("删除 value = " + value);
    }

    // session中替换值
    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {
        String name = event.getName();
        Object value = event.getValue();
        System.out.println("替换 name = " + name);
        System.out.println("替换 value = " + value);
    }
}
